extends Control
var socket = WebSocketPeer.new()
var aaa = false
var ip = "192.168.1.6"
#var ip = "192.168.200.69"
var token = str(Time.get_ticks_msec())
var webSocketState=WebSocketPeer.STATE_CLOSED
@onready var item_list: ItemList = $GridContainer/ItemList
var items = []
#var my_set = HashSet.new()
func _ready() -> void:
	print('_ready')
	print(typeof(items))
	ENetMultiplayerPeer
	WebRTCMultiplayerPeer
	#socket.connect_to_url("ws://192.168.200.69:8080/XhrServer/chat?token=123")

func _process(delta):
	socket.poll()  # 关键：每帧轮询

	match socket.get_ready_state():
		WebSocketPeer.STATE_OPEN:
			_receive_data()
		WebSocketPeer.STATE_CLOSED:
			if webSocketState!=WebSocketPeer.STATE_CLOSED:
				webSocketState =WebSocketPeer.STATE_CLOSED
				print("连接关闭！代码:", socket.get_close_code(), " 原因:", socket.get_close_reason())

	#if aaa:
		#socket.poll()
		#var state = socket.get_ready_state()
		#if state == WebSocketPeer.STATE_OPEN:
			#while socket.get_available_packet_count():
				#var binary_data: PackedByteArray = socket.get_packet()
				#var text = binary_data.get_string_from_utf8()
				#print("数据包：", text)
		#elif state == WebSocketPeer.STATE_CLOSING:
			## 继续轮询才能正确关闭。
			#pass
		#elif state == WebSocketPeer.STATE_CLOSED:
			#var code = socket.get_close_code()
			#var reason = socket.get_close_reason()
			#print("WebSocket 已关闭，代码：%d，原因 %s。干净得体：%s" % [code, reason, code != -1])
			#set_process(false) # 停止处理。


func _on_button_pressed() -> void:
	print("_on_button_pressed")
	var mError = socket.connect_to_url("ws://"+ip+":8080/XhrServer/chat?token="+token)
	if mError != OK:
		print("连接失败: ")
		aaa = false
	else :
		print("连接成功: ")
		aaa = true

func _on_button_2_pressed() -> void:
	socket.close(1000,token)
	aaa = false

func _receive_data():
	webSocketState =WebSocketPeer.STATE_OPEN
	while socket.get_available_packet_count() > 0:
		var packet = socket.get_packet()
		if socket.was_string_packet():
			var json = packet.get_string_from_utf8()
			print(json)
			var data = JSON.parse_string(json)
			if "0"==data["type"]:
				if item_list.item_count>0:
					if not item_list.has(data["sender"]):
						item_list.add_item(data["sender"])
				else :
					item_list.add_item(data["sender"])
			elif "1"==data["type"]:
				for i in range(item_list.item_count - 1, -1, -1):
					if item_list.get_item_text(i) == data["sender"]:
						item_list.remove_item(i)
		else:
			print("二进制:", packet)

func _exit_tree():
	socket.close()  # 退出时关闭连接
	

func _on_item_list_item_clicked(index: int, at_position: Vector2, mouse_button_index: int) -> void:
	print(item_list.get_item_text(index))
